package br.com.dev.tcc.adapter;

import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import br.com.dev.tcc.R;
import br.com.dev.tcc.bean.BaseItem;

public class GridBaseAdapter extends BaseAdapter {

	private Context ctx;
	private LayoutInflater inflater;
	private List<BaseItem> itens;
	private OnItemClickListener listener;

	public GridBaseAdapter(Context ctx, List<BaseItem> itens) {

		this.ctx = ctx;
		this.inflater = LayoutInflater.from(ctx);
		this.itens = itens;
	}

	@Override
	public int getCount() {

		return itens.size();
	}

	@Override
	public Object getItem(int position) {

		return itens.get(position);
	}

	@Override
	public long getItemId(int position) {

		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		convertView = inflater.inflate(R.layout.item_grid, null);

		((TextView) convertView.findViewById(R.id.text)).setText(itens.get(
				position).getText());

		ImageView icon = (ImageView) convertView.findViewById(R.id.icon);
		icon.setImageResource(itens.get(position).getIcon());

		if (listener != null) {

			convertView.setOnClickListener(new OnItemClickListenerAdapter(ctx,
					icon, position, position));
		}

		return convertView;
	}

	public void setOnItemClickListener(OnItemClickListener listener) {

		this.listener = listener;
		notifyDataSetChanged();
	}

	class OnItemClickListenerAdapter implements OnClickListener {

		private View view;
		private int position, id;
		private Context ctx;

		public OnItemClickListenerAdapter(Context ctx, View view, int position,
				int id) {

			this.ctx = ctx;
			this.view = view;
			this.position = position;
			this.id = id;
		}

		@Override
		public void onClick(final View v) {

			view.startAnimation(AnimationUtils.loadAnimation(ctx,
					R.anim.scale_accelerate));

			Handler h = new Handler(){
				
				@Override
				public void handleMessage(Message msg) {

					listener.onItemClick(null, v, position, id);
				}
			};
			
			h.sendEmptyMessageDelayed(0, 250);
		}
	}
}
